package com.example.charge;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class BatteryMonitor {
    private Context mContext;
    private BroadcastReceiver mReceiver;
    private OnChargeStateChangeListener mListener;
    private boolean isCharging = false;

    // 充电状态回调接口
    public interface OnChargeStateChangeListener {
        void onChargeStarted();  // 开始充电
        void onChargeStopped();  // 停止充电
    }

    public BatteryMonitor(Context context) {
        mContext = context.getApplicationContext();
        initReceiver();
    }

    private void initReceiver() {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    // 获取充电状态
                    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                    boolean currentlyCharging = chargePlug == BatteryManager.BATTERY_PLUGGED_AC 
                            || chargePlug == BatteryManager.BATTERY_PLUGGED_USB 
                            || chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;

                    // 状态变化时回调
                    if (currentlyCharging && !isCharging) {
                        isCharging = true;
                        if (mListener != null) {
                            mListener.onChargeStarted();
                        }
                    } else if (!currentlyCharging && isCharging) {
                        isCharging = false;
                        if (mListener != null) {
                            mListener.onChargeStopped();
                        }
                    }
                }
            }
        };
    }

    // 开始监控
    public void startMonitoring() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mContext.registerReceiver(mReceiver, filter);
    }

    // 停止监控
    public void stopMonitoring() {
        try {
            mContext.unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 设置回调监听
    public void setOnChargeStateChangeListener(OnChargeStateChangeListener listener) {
        mListener = listener;
    }
}